package jnpf.base.service.impl;

import jnpf.base.UserInfo;
import jnpf.base.model.base.SystemBaeModel;
import jnpf.base.service.SuperServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnpf.base.entity.*;
import jnpf.base.mapper.SystemMapper;
import jnpf.base.service.*;
import jnpf.constant.JnpfConst;
import jnpf.constant.PermissionConst;
import jnpf.permission.entity.OrganizeAdministratorEntity;
import jnpf.permission.entity.PermissionGroupEntity;
import jnpf.permission.service.AuthorizeService;
import jnpf.permission.service.OrganizeAdministratorService;
import jnpf.permission.service.PermissionGroupService;
import jnpf.util.JsonUtil;
import jnpf.util.RandomUtil;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月27日 上午9:18
 */
@Service
public class SystemServiceImpl extends SuperServiceImpl<SystemMapper, SystemEntity> implements SystemService {

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private ModuleService moduleService;
    @Autowired
    private AuthorizeService authorizeApi;
    @Autowired
    private OrganizeAdministratorService organizeAdminTratorApi;
    @Autowired
    private PermissionGroupService permissionGroupApi;

    @Override
    public List<SystemEntity> getList(String keyword, Boolean filterEnableMark, Boolean filterMain) {
        return getList(keyword, filterEnableMark, false, filterMain, false);
    }

    @Override
    public List<SystemEntity> getList(String keyword, Boolean filterEnableMark, boolean verifyAuth, Boolean filterMain, boolean isList) {
        List<String> systemIds = new ArrayList<>();
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        // 是否为列表，特殊处理
        if (isList) {
            // 获取系统菜单
            List<OrganizeAdministratorEntity> listByUserId = organizeAdminTratorApi.getOrganizeAdministratorEntity(UserProvider.getLoginUserId(), PermissionConst.SYSTEM, false);
            List<SystemEntity> systemEntities = this.getListByIds(listByUserId.stream().map(OrganizeAdministratorEntity::getOrganizeId).collect(Collectors.toList()));
            systemIds.addAll(systemEntities.stream().map(SystemEntity::getId).collect(Collectors.toList()));
        }
        if (StringUtil.isNotEmpty(keyword)) {
            queryWrapper.lambda().and(t ->
                    t.like(SystemEntity::getFullName, keyword).or().like(SystemEntity::getEnCode, keyword)
            );
        }
        if (filterEnableMark) {
            queryWrapper.lambda().eq(SystemEntity::getEnabledMark, 1);
        }
        if (verifyAuth) {
            List<String> currentUserSystem = getCurrentUserSystem(userProvider.get());
            if (currentUserSystem.size() == 0) {
                return new ArrayList<>();
            }
            systemIds.addAll(currentUserSystem);
            queryWrapper.lambda().in(SystemEntity::getId, systemIds);
        }
        // 过滤掉开发平台
        if (filterMain != null && filterMain) {
            queryWrapper.lambda().ne(SystemEntity::getEnCode, JnpfConst.MAIN_SYSTEM_CODE);
        }
        queryWrapper.lambda().orderByAsc(SystemEntity::getSortCode).orderByDesc(SystemEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

    @Override
    public List<String> getCurrentUserSystem(UserInfo userInfo) {
        List<SystemBaeModel> systemList = new ArrayList<>(16);
        if (!userInfo.getIsAdministrator()) {
            List<String> roleIds = permissionGroupApi.getPermissionGroupByUserId(userInfo.getUserId(), null, false)
                    .stream().map(PermissionGroupEntity::getId).collect(Collectors.toList());
            if (roleIds.size() > 0) {
                systemList = authorizeApi.findSystem(roleIds);
            }
        } else {
            List<SystemEntity> systemLists = this.getList(null, false, false);
            systemList = JsonUtil.getJsonToList(systemLists, SystemBaeModel.class);
        }
        SystemEntity entity = this.getInfo(userInfo.getSystemId());
        if (entity != null) {
            SystemBaeModel jsonToBean = JsonUtil.getJsonToBean(entity, SystemBaeModel.class);
            SystemBaeModel systemBaeModel = systemList.stream().filter(t -> t.getId().equals(jsonToBean.getId())).findFirst().orElse(null);
            if (systemBaeModel == null) {
                systemList.add(jsonToBean);
            }
        }
        return systemList.stream().map(SystemBaeModel::getId).collect(Collectors.toList());
    }

    @Override
    public SystemEntity getInfo(String id) {
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SystemEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public Boolean isExistFullName(String id, String fullName) {
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SystemEntity::getFullName, fullName);
        if (StringUtil.isNotEmpty(id)) {
            queryWrapper.lambda().ne(SystemEntity::getId, id);
        }
        return this.count(queryWrapper) > 0;
    }

    @Override
    public Boolean isExistEnCode(String id, String enCode) {
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SystemEntity::getEnCode, enCode);
        if (StringUtil.isNotEmpty(id)) {
            queryWrapper.lambda().ne(SystemEntity::getId, id);
        }
        return this.count(queryWrapper) > 0;
    }

    @Override
    @Transactional
    public Boolean create(SystemEntity entity) {
        entity.setId(RandomUtil.uuId());
        entity.setIsMain(0);
        entity.setCreatorUserId(userProvider.get().getUserId());
        entity.setCreatorTime(new Date());
        boolean save = this.save(entity);
        if (!userProvider.get().getIsAdministrator() && save) {
            // 当前用户创建的组织要赋予权限
            OrganizeAdministratorEntity organizeAdministratorEntity = new OrganizeAdministratorEntity();
            organizeAdministratorEntity.setUserId(userProvider.get().getUserId());
            organizeAdministratorEntity.setOrganizeId(entity.getId());
            organizeAdministratorEntity.setOrganizeType(PermissionConst.SYSTEM);
            organizeAdminTratorApi.save(organizeAdministratorEntity);
        }
        return save;
    }

    @Override
    @Transactional
    public Boolean update(String id, SystemEntity entity) {
        entity.setId(id);
        if (entity.getIsMain() == null) {
            entity.setIsMain(0);
        }
        entity.setLastModifyUserId(userProvider.get().getUserId());
        entity.setLastModifyTime(new Date());
        return this.updateById(entity);
    }

    @Override
    @Transactional
    public Boolean delete(String id) {
        moduleService.deleteBySystemId(id);
        return this.removeById(id);
    }

    @Override
    public List<SystemEntity> getListByIds(List<String> list) {
        List<SystemEntity> systemList = new ArrayList<>(16);
        if (list.size() > 0) {
            QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(SystemEntity::getId, list);
            queryWrapper.lambda().eq(SystemEntity::getEnabledMark, 1);
            queryWrapper.lambda().orderByAsc(SystemEntity::getSortCode).orderByDesc(SystemEntity::getCreatorTime);
            return this.list(queryWrapper);
        }
        return systemList;
    }

    @Override
    public SystemEntity getMainSystem() {
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SystemEntity::getIsMain, 1);
        List<SystemEntity> list = this.list(queryWrapper);
        if (list.size() > 0) {
            return list.get(0);
        }
        List<SystemEntity> list1 = getList(null, true, false);
        if (list1.size() > 0) {
            return list1.get(0);
        }
        return new SystemEntity();
    }

    @Override
    public List<SystemEntity> getMainSys(List<String> systemIds) {
        if (systemIds.size() == 0) {
            return new ArrayList<>();
        }
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(SystemEntity::getId, systemIds);
        queryWrapper.lambda().eq(SystemEntity::getIsMain, 1);
        return this.list(queryWrapper);
    }

    @Override
    public SystemEntity getInfoByEnCode(String enCode) {
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SystemEntity::getEnCode, enCode);
        return this.getOne(queryWrapper);
    }

}
